package com.ldap;

import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;

public class LdapAction {

    DirContext ctx = null;

    public static void main(String[] args) {
        LdapAction LA = new LdapAction();
        LA.add();
    }

    public LdapAction() {
        LdapQuery query = new LdapQuery();

        try {
            ctx = query.init("administrator" + LdapQuery.DOMAIN, "bod;rvsomsdf,[");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void add() {
        try {

            String newUserName = "test_add_6";
            BasicAttributes attrs = new BasicAttributes();

            BasicAttribute objclass = new BasicAttribute("Objectclass");
            objclass.add("organizationalPerson");
            objclass.add("person");
            objclass.add("top");
            objclass.add("user");
            attrs.put(objclass);

            attrs.put("userPrincipalName", newUserName + LdapQuery.DOMAIN);
            attrs.put("userpassword", "123456");
            attrs.put("sAMAccountName", newUserName);

            String userpassword = "\"" + "123456789" + "\"";
            byte[] unicodePassword = userpassword.getBytes("UTF-16LE");
            // attrs.put("unicodePwd", unicodePassword);

            // 以下cn 顺便生成了 name, cn属性
            ctx.createSubcontext("CN=" + newUserName
                    + ",OU=SDMP,OU=AllUsers,DC=fhtesc,DC=fiberhome,DC=com,DC=cn", attrs);// fhtesc.fiberhome.com.cn

        } catch (Exception e) {
            System.out.println("Exception in add():" + e);
        }
    }
}